package org.dromara.system.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.constant.MachineConstant;
import org.dromara.system.domain.SimUserRenewal;
import org.dromara.system.domain.bo.SimUserRenewalBo;
import org.dromara.system.domain.vo.SimUserRenewalVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SimUserRenewalMapper;
import org.dromara.system.service.ISimUserRenewalService;
import org.dromara.system.service.ISysUserService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

/**
 * 续期成本Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SimUserRenewalServiceImpl extends ServiceImpl<SimUserRenewalMapper, SimUserRenewal>
    implements ISimUserRenewalService {

    private final ISysUserService sysUserService;
    private final PermissionBaseService permissionBaseService;

    /**
     * 查询续期成本
     *
     * @param id 主键
     * @return 续期成本
     */
    @Override
    public SimUserRenewalVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询续期成本列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 续期成本分页列表
     */
    @Override
    public TableDataInfo<SimUserRenewalVo> queryPageList(SimUserRenewalBo bo, PageQuery pageQuery) {
        IPage<SimUserRenewalVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SimUserRenewalVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的续期成本列表
     *
     * @param bo 查询条件
     * @return 续期成本列表
     */
    @Override
    public List<SimUserRenewalVo> queryList(SimUserRenewalBo bo) {
        LambdaQueryWrapper<SimUserRenewal> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SimUserRenewal> buildQueryWrapper(SimUserRenewalBo bo) {
        LambdaQueryWrapper<SimUserRenewal> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SimUserRenewal::getId);
        lqw.eq(bo.getUserId() != null, SimUserRenewal::getUserId, bo.getUserId());
        lqw.eq(bo.getYearNum() != null, SimUserRenewal::getYearNum, bo.getYearNum());
        lqw.eq(bo.getRenewalAmount() != null, SimUserRenewal::getRenewalAmount, bo.getRenewalAmount());
        return lqw;
    }

    @Override
    public Boolean saveOrUpdate(SimUserRenewalBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SimUserRenewal add = MapstructUtils.convert(bo, SimUserRenewal.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insertOrUpdate(add);
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }


    /**
     * 新增续期成本
     *
     * @param bo 续期成本
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SimUserRenewalBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SimUserRenewal add = MapstructUtils.convert(bo, SimUserRenewal.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }


    /**
     * 修改续期成本
     *
     * @param bo 续期成本
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SimUserRenewalBo bo) {
        SimUserRenewal update = MapstructUtils.convert(bo, SimUserRenewal.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SimUserRenewal entity) {
//        int size = lambdaQuery().eq(SimUserRenewal::getUserId, entity.getUserId()).list().size();
        BusinessException.isTrue(ObjectUtil.notEqual(entity.getYearNum(), MachineConstant.NUMBER.ONE), "只能添加一条续期年数为1的数据");
        BigDecimal renewalAmount = entity.getRenewalAmount();
        SysUserVo sysUserVo = sysUserService.selectUserById(entity.getUserId());
        SimUserRenewal simUserRenewal = lambdaQuery()
            .eq(SimUserRenewal::getUserId, sysUserVo.getPId())
            .eq(SimUserRenewal::getYearNum, MachineConstant.NUMBER.ONE).one();
        BusinessException.isNull(simUserRenewal, "上级续期成本未设置");
        BusinessException.isTrue(NumberUtil.isLess(renewalAmount, simUserRenewal.getRenewalAmount())
            , "成本最低为" + simUserRenewal.getRenewalAmount() + "元");
    }

    /**
     * 校验并批量删除续期成本信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


}
